package com.yonyou.crm.sys.user.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.yonyou.crm.bpub.refervalue.entity.ReferDataVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.entity.EnableStateEnum;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.model.util.ModelUtil;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.pinyin.PinyinToolkit;
import com.yonyou.crm.common.rowstate.constant.RowStateConstant;
import com.yonyou.crm.csns.phonebook.service.PersonBizServiceImpl;
import com.yonyou.crm.sys.org.entity.SysOrgVO;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.role.entity.RoleVO;
import com.yonyou.crm.sys.role.service.RoleBizServiceImpl;
import com.yonyou.crm.sys.user.entity.JobEnum;
import com.yonyou.crm.sys.user.entity.TypeEnum;
import com.yonyou.crm.sys.user.entity.UserDO;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.itf.IUserBizService;
import com.yonyou.crm.sys.user.util.SecurityUtil;
import com.yonyou.iuap.context.InvocationInfoProxy;

public class UserBizServiceImpl extends BaseBizServiceImpl<UserDO> implements IUserBizService{
	
	@Autowired
	private SysOrgBizServiceImpl orgService;
	@Autowired
	private EnumBizServiceImpl enumService;
	@Autowired
	private RoleBizServiceImpl roleService;
	
	@Autowired
	private PersonBizServiceImpl phonebookService;
	
	/**
	 * 根据用户名获得用户
	 * @param userName
	 * @return
	 */
	public UserVO getUserByUserName(String userName){
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("userName", userName);
				
		List<Map<String, Object>> userList = dao.selectList(UserDO.class, "getUserByUserName", paraMap);
		if (userList != null && userList.size() >0) {
			
			UserDO uDO = (UserDO)userList.get(0);
			UserVO uVO = ModelUtil.copyModel(uDO, UserVO.class);
			//设置角色
			RoleVO roleVO = getRoleByUserId(uVO.getId());
			if (roleVO != null) {
				uVO.setRoleId(roleVO.getId());
				uVO.setRoleType(roleVO.getType());
			}

			return uVO;
		}
		return null;
	}
	
	/**
	 * 分页列表
	 */
	public Page<UserVO> getPage(Page<UserVO> page,Map<String, Object> paraMap) {	
		
		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		
		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		
		//排除当前登录人
		paraMap.put("userId", new Long(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
		
		//组织过滤
		int userType = getUserTypeById(new Long(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
		if (userType == TypeEnum.GSADMIN.getValue()) {
			paraMap.put("orgId", InvocationInfoProxy.getParameter(LoginContextConstant.OrgId));
		}
		
		Page<UserDO> doPage = super.pageSelect(UserDO.class, page, paraMap.keySet().toArray(new String[0]), paraMap.values().toArray(new Object[0]));
		
		Page<UserVO> voPage = ModelUtil.copyPageModel(doPage, UserVO.class); 
		
		//设置角色
		List<UserVO> voList = voPage.getData();
		for (UserVO vo : voList) {
			
			vo.setRoleId(getRoleIdByUserId(vo.getId()));
		}
		
		trans(voList);

		return voPage;
	}
	
	/**
	 * 详情
	 */
	public UserVO getDetail(Long id) {
		
		UserDO userDO = super.getVOById(UserDO.class, id);
		UserVO vo = ModelUtil.copyModel(userDO, UserVO.class);
		if(vo==null)
			return null;
		//设置角色
		vo.setRoleId(getRoleIdByUserId(vo.getId()));
		
		trans(Arrays.asList(vo));
		return vo;
	}
	
	/**
	 * 新增
	 */
	public UserVO insert(UserVO vo) {
		
		UserDO uDO = super.saveVO(ModelUtil.copyModel(vo, UserDO.class));
		
		//分配角色
		Long roleId = vo.getRoleId();
		if (roleId != null) {
			roleService.assignUserRole(new String[]{roleId.toString()}, new String[]{uDO.getId().toString()});
		}
		
		vo = ModelUtil.copyModel(uDO, UserVO.class);
		
		vo.setEnableState(EnableStateEnum.ENABLE.getValue());
		vo.setRoleId(roleId);
		
		trans(Arrays.asList(vo));
		
		return vo;
	}
	
	@Override
	protected void beforeSaveVO(UserDO uDO) {
		
		super.beforeSaveVO(uDO);
		
		int phoneCount = getUserCountByPhone(uDO.getPhone(), null);
		if (phoneCount > 0) {
			throw new CrmBusinessException("手机号已存在");
		}
		
		int emailCount = getUserCountByEmail(uDO.getEmail(), null);
		if (emailCount > 0) {
			throw new CrmBusinessException("邮箱已存在");
		}

		//设置名称拼音
		uDO.setNamePinyin(PinyinToolkit.cn2Spell(uDO.getName(), 1));
		
		if (StringUtils.isBlank(uDO.getEmail())) {
			uDO.setEmail(null);
		}
		if(uDO.getOrgId() == null || uDO.getOrgId().intValue() == 0) {
			String orgId = InvocationInfoProxy.getParameter("orgid");
			uDO.setOrgId(Long.parseLong(orgId));
		}
		if(uDO.getJob() == null || uDO.getJob().intValue() == 0) {
			uDO.setJob(JobEnum.STAFF.getValue());
		}
		if(uDO.getGender() == null || uDO.getGender().intValue() == 0) {
			uDO.setGender(1);
		}
		if(uDO.getType() == null || uDO.getType().intValue() == 0) {
			uDO.setType(TypeEnum.USER.getValue());
		}

		uDO.setTenantId(new Long(InvocationInfoProxy.getTenantid()));
		
		//设置初始密码
		String salt = SecurityUtil.generateSalt();
		String password = SecurityUtil.generateEncryptStr("111111", salt);
		uDO.setPassword(password);
		uDO.setSalt(salt);
		
		uDO.setEnableTime(new Date());
		uDO.setEnableUserId(new Long(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
	}
	
	@Override
	protected void afterSaveVO(UserDO uDO) {
		super.afterSaveVO(uDO);
		
		// 同步通讯录(2017-10-26shenhui)
		phonebookService.synPersonData();
	}
	
	/**
	 * 修改
	 */
	public UserVO update(UserVO vo) {
		
		UserDO uDO = super.updateVO(ModelUtil.copyModel(vo, UserDO.class));

		Long roleId = getRoleIdByUserId(vo.getId());
		Long newRoleId = vo.getRoleId();
		String[] userIds = new String[]{vo.getId().toString()};
		
		vo = ModelUtil.copyModel(uDO, UserVO.class);
		
		if (roleId != null && newRoleId != null) {
			//修改用户角色
			if (newRoleId.intValue() != roleId.intValue()) {
				roleService.unAssignUser(roleId, userIds);
				roleService.assignUserRole(new String[]{newRoleId.toString()}, userIds);
			}
		}
		else if(roleId == null && newRoleId != null) {
			//增加用户角色
			roleService.assignUserRole(new String[]{newRoleId.toString()}, userIds);
		}
		else if(roleId != null && newRoleId == null) {
			//删除用户角色
			roleService.unAssignUser(roleId, new String[]{vo.getId().toString()});
		}
		
		//用于列表展示
		vo.setRoleId(newRoleId);
		
		trans(Arrays.asList(vo));
		
		return vo;
	}
	
	@Override
	protected void beforeUpdateVO(UserDO uDO) {
		
		int phoneCount = getUserCountByPhone(uDO.getPhone(), uDO.getId());
		if (phoneCount > 0) {
			throw new CrmBusinessException("手机号已存在");
		}
		
		int emailCount = getUserCountByEmail(uDO.getEmail(), uDO.getId());
		if (emailCount > 0) {
			throw new CrmBusinessException("邮箱已存在");
		}
		
		super.beforeUpdateVO(uDO);
		
		//设置名称拼音
		uDO.setNamePinyin(PinyinToolkit.cn2Spell(uDO.getName(), 1));
	}
	
	
	@Override
	protected void afterUpdateVO(UserDO uDO) {
		super.afterUpdateVO(uDO);
		
		// 同步通讯录(2017-10-26shenhui)
		phonebookService.synPersonData();
	}
	
	public int delete(Long id) {
		UserDO uDO = new UserDO();
		uDO.setId(id);
		return super.deleteVO(uDO);
	}
	
	/**
	 * 批量删除
	 */
	public String batchDelete(String[] ids) {
		
		String message = "";
		
		Set<String> idSet = new HashSet<String>();
		for (String id : ids) {
			idSet.add(id);
		}
		
		StringBuffer ownName = new StringBuffer();
		//是否有负责的客户、商机
		List<Map<String, Object>> objList = getOwnBusObj(ids);
		if (objList != null && objList.size() > 0) {
			
			for (Map<String, Object> obj : objList) {
				//过滤掉不能删除的人员
				idSet.remove(obj.get("id").toString());
				//记录不能删除人员姓名
				ownName.append(obj.get("name"));
			}
			
			ids = idSet.toArray(new String[0]);
			
			message = "【" + ownName.toString() + "】有负责的客户或商机，不允许删除，需要进行数据移交。";
		}
		else {
			message = "删除成功。";
		}
		
		if (ids.length > 0) {
			super.batchDeleteByIDs(UserDO.class, ids);
			//删除用户角色
			roleService.userDelRole(ids);
			// 同步通讯录(2017-10-26shenhui)
			phonebookService.synPersonData();
		}

		return message;
	}
	
	/**
	 * 批量停启用
	 */
	public String batchUpdateEnableState(String[] ids, Integer enableState) {
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		String message = "";
		
		if (enableState.intValue() == EnableStateEnum.DISABLE.getValue()) {
			
			//停用时取消负责人、其他负责人
			paraMap.put("job", JobEnum.STAFF.getValue());//普通员工
			
			Set<String> idSet = new HashSet<String>();
			for (String id : ids) {
				idSet.add(id);
			}
			
			StringBuffer ownName = new StringBuffer();
			//是否有负责的客户、商机
			List<Map<String, Object>> objList = getOwnBusObj(ids);
			if (objList != null && objList.size() > 0) {
				
				for (Map<String, Object> obj : objList) {
					//过滤掉不能停用的人员
					idSet.remove(obj.get("id").toString());
					//记录不能停用人员姓名
					ownName.append(obj.get("name"));
				}
				
				ids = idSet.toArray(new String[0]);
				
				message = "【" + ownName.toString() + "】有负责的客户或商机，不允许停用，需要进行数据移交。";
			}
			else {
				message = "停用成功。";
			}
		}
		else {
			message = "启用成功。";
		}
		
		if (ids.length > 0) {
			
			paraMap.put("ids", ids);
			paraMap.put("enableState", enableState);
			paraMap.put("enableUserId", new Long(InvocationInfoProxy.getParameter("id")));
			paraMap.put("enableTime", new Date());
				
			dao.updateSql(UserDO.class, "batchUpdateEnableState", paraMap);
			
			// 同步通讯录(2017-10-26shenhui)
			phonebookService.synPersonData();
		}

		return message;
	}
	
	public int getUserCountByEmail(String email, Long id) {
		
		if (StringUtils.isBlank(email)) {
			return 0;
		}
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("email", email);
		paraMap.put("excludeId", id);
		return getCountByCondition(paraMap);
	}
	
	public int getUserCountByPhone(String phone, Long id) {
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("phone", phone);
		paraMap.put("excludeId", id);
		return getCountByCondition(paraMap);
	}

	public int getUserCountByJob(Long orgId) {
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("orgId", orgId);
		paraMap.put("job", JobEnum.STAFF.getValue());
		return getCountByCondition(paraMap);
	}
	
	/**
	 * 根据条件查询用户数量
	 * @param paraMap
	 * @return
	 */
	public int getCountByCondition(Map<String, Object> paraMap) {
		return dao.countAll(UserDO.class, "getCountByCondition", fillParaMapWithTenantId(paraMap));
	}
	
	/**
	 * 获得部门下的销售经理
	 * @param deptId
	 * @return
	 */
	public List<String> getSMIdListByDeptId(Long deptId) {
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("deptId", deptId);
		paraMap.put("roleId", 2);//销售经理
		return getIdListByCondition(paraMap);
	}
	
	/**
	 * 根据条件获得人员id列表
	 * @param paraMap
	 * @return
	 */
	public List<String> getIdListByCondition(Map<String, Object> paraMap) {
		return dao.selectStrList(UserDO.class, "getIdListByCondition", fillParaMapWithTenantId(paraMap));
	}
	
	public Object selectFieldsByIds(Object[] ids) {
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		return dao.selectList(UserDO.class, "selectFieldsByIds", para);
	}

	private List<UserVO> trans(List<UserVO> userList) {
		
		if (userList != null && userList.size() > 0) {
			
			List<FieldRelation<UserVO>> relations = new ArrayList<FieldRelation<UserVO>>();
			relations.add(new RefFieldRelation<UserVO>(UserVO.class, "deptId", new String[]{"deptName"}, orgService, "selectFieldsByIds"));
			relations.add(new RefFieldRelation<UserVO>(UserVO.class, "orgId", new String[]{"orgName"}, orgService, "selectFieldsByIds"));
			relations.add(new RefFieldRelation<UserVO>(UserVO.class, "roleId", new String[]{"roleName"}, roleService, "selectFieldsByIds"));
			relations.add(new EnumFieldRelation<UserVO>(UserVO.class, "gender", "genderName", enumService, "gender"));
			relations.add(new EnumFieldRelation<UserVO>(UserVO.class, "job", "jobName", enumService, "job"));
			relations.add(new EnumFieldRelation<UserVO>(UserVO.class, "enableState", "enableStateName", enumService, "enable_state"));
			
			new FieldRelationHandler<UserVO>().handler(userList, relations);
			
			//转换用户类型
			for (UserVO user : userList) {
				Integer type = user.getType();
				if (type != null) {
					List<Integer> typeList = new ArrayList<>();
					for(TypeEnum typeEnum : TypeEnum.values()){
						typeList.add(typeEnum.getValue());
					}
					String typeName = "";
					if (typeList.contains(type)) {
						for(TypeEnum typeEnum : TypeEnum.values()){
							if (type == typeEnum.getValue()) {
								typeName = typeEnum.getName();
							}
						}
					}
					user.setTypeName(typeName);
				}
			}
		}

		return userList;
	}
	
	/**
	 * 根据用户id获得角色
	 * @param userId
	 * @return
	 */
	private Long getRoleIdByUserId(Long userId) {
		
		RoleVO roleVO = getRoleByUserId(userId);
		if (roleVO != null) {
			return roleVO.getId();
		}
		return null;
	}
	
	private RoleVO getRoleByUserId(Long userId) {
		List<RoleVO> roleList = roleService.getUserRole(userId);
		if (roleList != null && roleList.size() > 0) {
			return roleList.get(0);
		}
		return null;
	}
	
	@Override
	protected void afterDeleteVO(UserDO uDO) {
		super.afterDeleteVO(uDO);
		
		// 同步通讯录(2017-10-26shenhui)
		phonebookService.synPersonData();
	}

	public List<ReferDataVO> getRefervalues(Page<ReferDataVO> page, Map<String, Object> paraMap) {
		// TODO 加权限
		Page<UserDO> pageVO = dao.pageSelect(UserDO.class, page, "selectRefervalues", "countRefervalues", paraMap);
		List<UserDO> voList = pageVO.getData();
		
		List<ReferDataVO> rsList = new ArrayList<ReferDataVO>();
		for (UserDO vo : voList) {
			ReferDataVO referDataVO = new ReferDataVO();
			referDataVO.setId(vo.getId().toString());
			referDataVO.setValue(vo.getName());
			
			rsList.add(referDataVO);
		}
		return rsList;
	}
	
	public List<UserVO> getRefervaluesForApp(Page<UserVO> page, Map<String, Object> paraMap) {
		// TODO 加权限
		//移动端  人员通用参照改为不分页的
		//Page<UserDO> doPage = dao.pageSelect(UserDO.class, page, "selectRefervalues", "countRefervalues", paraMap);
		List<UserDO> userList = dao.selectVoList(UserDO.class, "selectRefervaluesForApp", paraMap);
		List<UserVO> userVOS = ModelUtil.copyModelList(userList, UserVO.class);
		List<UserVO> userVOList = trans(userVOS);
		//List<UserVO> voList = voPage.getData();
		return userVOList;
	}
	
	public List<UserVO> getAdminList(Map<String, Object> paramMap){
		List<UserDO> doList = dao.selectVoList(UserDO.class, "getAdminList", paramMap);
		List<UserVO> voList = ModelUtil.copyModelList(doList, UserVO.class);
		trans(voList);
		return voList;
	}
	
	/**
	 * 获取登录信息
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getLoginContext(Long userId) {
		return (Map<String, Object>) dao.selectOne(UserDO.class, "getLoginContext", userId);
	}
	
	/**
	 * 获取下属部门及人员
	 * @param paramMap
	 * @return
	 */
	public Map<String, Object> getDeptAndUserList(Map<String, Object> paramMap){
		Map<String, Object> res = new HashMap<String, Object>();
		List<Map<String, Object>> users = new ArrayList<>();
		List<UserDO> doList = dao.selectVoList(UserDO.class, "selectUsersListByDeptId", paramMap);
		List<UserVO> voList = ModelUtil.copyModelList(doList, UserVO.class);
		trans(voList);
		for(int i = 0; i < voList.size(); i++) {
			UserVO user = voList.get(i);
			Map<String, Object> userInfo = new HashMap<>();
			userInfo.put("id", user.getId());
			userInfo.put("name", user.getName());
			userInfo.put("deptname", user.getDeptName());
			users.add(userInfo);
		}
		res.put("personlist", users);
		List<Map<String, Object>> depts = orgService.getOrgByFatherId(paramMap);
		res.put("deptlist", depts);
		return res;
	}
	
	public List<Map<String, Object>> getUserByDeptId(Long deptId, String condition) {
		if (deptId == null || deptId.equals(0L)) {
			String deptIdStr = (String)InvocationInfoProxy.getParameter("deptid");//所属部门
			deptId = Long.parseLong(deptIdStr);
		}
		
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("deptId", deptId);
		para.put("condition", condition);
		List<UserDO> userList = dao.selectVoList(UserDO.class, "getUserByDeptId", para);
		List<UserVO> userVOS = ModelUtil.copyModelList(userList, UserVO.class);
		List<UserVO> userVOList = trans(userVOS);
		List<Map<String, Object>> returnList = new ArrayList<>();
		if(userVOList != null && userVOList.size() > 0) {
			for (UserVO userVO : userVOList) {
				Map<String, Object> map = new HashMap<>();
				map.put("id", userVO.getId());
				map.put("name", userVO.getName());
				map.put("pic", "");
				map.put("dept", userVO.getDeptName());
				returnList.add(map);
			}
		}
		return returnList;
	}
	
	public Page<UserVO> getOrgUserList(Page<UserVO> page,Map<String, Object> paramMap) {
		
		if (paramMap == null) {
			paramMap = new HashMap<String, Object>();
		}
		paramMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		paramMap.put("orgId", new Long(InvocationInfoProxy.getParameter(LoginContextConstant.OrgId)));
		paramMap.put("enableState", "1");
		
		Page<UserDO> doPage = super.pageSelect(UserDO.class, page, paramMap.keySet().toArray(new String[0]), paramMap.values().toArray(new Object[0]));
		
		Page<UserVO> voPage = ModelUtil.copyPageModel(doPage, UserVO.class);
		trans(voPage.getData());
		
		return voPage;
	}
	
	/**
	 * 根据部门id获取人员数量
	 * @param orgId
	 * @return
	 */
	public int getUserCountByDeptId(Long deptId) {
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("deptId", deptId);
		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		return dao.countAll(UserDO.class, "getUserCountByDeptId", paraMap);
	}
	
	/*
	 * 获取所有用户列表(For云审同步)
	 */
	public List<Map<String, Object>> getAllUsers() {
		Long tenantId = Long.parseLong(InvocationInfoProxy.getTenantid());
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", tenantId);
		return dao.selectList(UserDO.class, "getAllUsers", param);
	}
	
	public List<UserVO> getUserListExport(Map<String, Object> paramMap) {

		if (paramMap == null) {
			paramMap = new HashMap<>();
		}
		
		paramMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));

		List<UserDO> doList = dao.selectVoList(UserDO.class, "getUsersExport", paramMap);
		List<UserVO> voList = ModelUtil.copyModelList(doList, UserVO.class);
		trans(voList);
		return voList;
	}
	
	/**
	 * 根据id获取用户类型
	 * @param id
	 * @return
	 */
	public int getUserTypeById(Long id) {
		return Integer.parseInt((String)dao.selectOne(UserDO.class, "getUserTypeById", id));
	}
	
	/**
	 * 参照列表
	 * @param paraMap
	 * @return
	 */
	public List<UserVO> getRefList(Map<String, Object> paraMap) {

		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		
		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		
		List<UserDO> doList = dao.selectVoList(UserDO.class, "getRefList", paraMap);
		
		List<UserVO> voList = ModelUtil.copyModelList(doList, UserVO.class);
		
		trans(voList);
		
		return voList;
	}
	
	/**
	 * 分页参照列表
	 * @param page
	 * @param paraMap
	 * @return
	 */
	public Page<UserVO> getRefPage(Page<UserVO> page, Map<String, Object> paraMap) {

		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}

		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		
		Page<UserDO> dPage = dao.pageSelect(UserDO.class, page, "getRefPage", "countRefPage", paraMap);
		
		Page<UserVO> vPage = ModelUtil.copyPageModel(dPage, UserVO.class);
		
		trans(vPage.getData());
		
		return vPage;
	}
	
	/**
	 * 批量更新
	 * @param voList
	 * @return
	 */
	public List<UserVO> batchUpdateAdmin(List<UserVO> voList) {
		
		int userType = getUserTypeById(new Long(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
		
		List<UserVO> returnList = new ArrayList<UserVO>();
		for(UserVO vo : voList){
			
			
			
			UserDO uDO = ModelUtil.copyModel(vo, UserDO.class);
			
			if(vo.getEditState().equalsIgnoreCase(RowStateConstant.ADD)){
				
				//系统管理员创建集团管理员
				if (userType == TypeEnum.XTADMIN.getValue()) {
					uDO.setType(TypeEnum.JTADMIN.getValue());
				}
				//集团管理员创建公司管理员
				else if (userType == TypeEnum.JTADMIN.getValue()) {
					uDO.setType(TypeEnum.GSADMIN.getValue());
				}
				
				returnList.add(ModelUtil.copyModel(saveVO(uDO), UserVO.class));
			}else if(vo.getEditState().equalsIgnoreCase(RowStateConstant.UPDATE)){
				
				returnList.add(ModelUtil.copyModel(updateVO(uDO), UserVO.class));
			}else if(vo.getEditState().equalsIgnoreCase(RowStateConstant.DELETE)){
				
				delete(vo.getId());
			}else {
				//没有变更的也返回
				returnList.add(vo);
			}
		}
		
		trans(returnList);
		
		return returnList;
	}

	/**
	 * 分配角色
	 * @param userIds 用户id数据
	 * @param roleIds 角色id数据
	 */
	public void allocateRole(String[] userIds, Long roleId) {
		
		if (userIds == null || userIds.length == 0 || roleId == null) {
			return;
		}

		roleService.userDelRole(userIds);
		roleService.assignUserRole(new String[]{roleId.toString()}, userIds);
	}
	
	/**
	 * 修改密码
	 * @param userId 要修改的用户id
	 * @param password 要修改的密码
	 */
	public void updatePassword(Long userId, String password) {

		String salt = SecurityUtil.generateSalt();
		String encryptPwd = SecurityUtil.generateEncryptStr(password, salt);
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("id", userId);
		paraMap.put("password", encryptPwd);
		paraMap.put("salt", salt);
		
		dao.updateSql(UserDO.class, "updatePassword", paraMap);
	}
	
	/**
	 * 获取负责的业务对象
	 * @param ids
	 * @return
	 */
	public List<Map<String, Object>> getOwnBusObj(String[] ids) {
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("ids", ids);
		return dao.selectList(UserDO.class, "getOwnBusObj", paraMap);
	}
	
	private Map<String, Object> fillParaMapWithTenantId(Map<String, Object> paraMap) {
		
		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		
		paraMap.put("tenantId", InvocationInfoProxy.getTenantid());
		
		return paraMap;
	}

	@Override
	public List<Map<String, Object>> getSubdeptsForCurrentUser() {
	
		Map<String, Object> param = new HashMap<>();
		List<Map<String, Object>> depts = new ArrayList<>();
		String deptId = InvocationInfoProxy.getParameter(LoginContextConstant.DeptId);
		if (StringUtils.isNotBlank(deptId)) {
			param.put("orgId", new Long(deptId));
			List<SysOrgVO> orgVOs = orgService.getVosByCondition(param);
			
			if(orgVOs != null) {
				for(SysOrgVO orgVO : orgVOs) {
					Map<String, Object> orgMap = new HashMap<>();
					orgMap.put("id", orgVO.getId());
					orgMap.put("name", orgVO.getName());
					depts.add(orgMap);
				}
			}
		}

		return depts;
	}
	
}	
